using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Input;
using WpfWordsLearner.Helper;
using System.Threading.Tasks;

namespace WpfWordsLearner.ViewModels
{
	public class TranslateViewModel : BaseViewModel
	{
		public TranslateViewModel()
		{
			m_Translate = new Model.TranslateModel();
			m_Translate.Content = WpfWordsLearner.Properties.Resources.msgEnterText;
			m_Translate.FromLanguage = "en"; m_Translate.ToLanguage = "ru";

			FromLanguage = new List<string>();
			ToLanguage = new List<string>();
			FromLanguage.AddRange(new string[] { "en", "ru", "it", "ge", "ua" });
			ToLanguage.AddRange(new string[] { "ru", "en", "ge", "it", "ua" });
		}

		private Model.TranslateModel m_Translate = null;
		public Model.TranslateModel Request
		{
			get { return m_Translate; }
			set
			{
				m_Translate = value;
				base.OnPropertyChanged(() => Request);
			}
		}

		public List<string> FromLanguage { get; set; }
		public List<string> ToLanguage { get; set; }

		private bool needBusy;

		public bool NeedBusy
		{
			get { return needBusy; }
			set { needBusy = value; OnPropertyChanged(() => NeedBusy); }
		}

		private string m_result;

		public string Result
		{
			get { return m_result; }
			set
			{
				m_result = value;
				OnPropertyChanged(() => Result);
				OnPropertyChanged(() => Save);
			}
		}


		public ICommand Translate { get { return new BaseCommand(TranslateExecuted, new Func<bool>(CanTranslateExecute)); } }
		private void TranslateExecuted()
		{
			NeedBusy = true;
			var request = new ServiceReferenceTranslater.TranslationRequest();
			request.FromLanguage = Request.FromLanguage;
			request.ToLanguage = Request.ToLanguage;
			request.Content = Request.Content;

			Task translateTask = new Task(new Action(() =>
				{
					using (ServiceReferenceTranslater.TranslateServiceClient client = new ServiceReferenceTranslater.TranslateServiceClient())
					{
						var response = client.Translate(request);
						if (response != null)
						{
							Result = response.TranslationResult;
						}
					}
				}));

			translateTask.ContinueWith(prevTask =>
				{
					NeedBusy = false;
					App.Log.Error(WpfWordsLearner.Properties.Resources.erroOftranslation, prevTask.Exception);
					prevTask.Dispose();
				}, System.Threading.CancellationToken.None, TaskContinuationOptions.NotOnRanToCompletion, TaskScheduler.FromCurrentSynchronizationContext());

			translateTask.ContinueWith(prevTask =>
			{
				NeedBusy = false;
				prevTask.Dispose();
			}, System.Threading.CancellationToken.None, TaskContinuationOptions.OnlyOnRanToCompletion, TaskScheduler.FromCurrentSynchronizationContext());

			translateTask.Start();
		}

		private bool CanTranslateExecute()
		{
			return !string.IsNullOrEmpty(Request.Content);
		}

		public ICommand Save { get { return new BaseCommand(SaveExecuted, new Func<bool>(CanSaveExecute)); } }
		private void SaveExecuted()
		{
			ViewModels.Windows1ViewModel vm = (App.Current.MainWindow as WpfWordsLearner.Views.Window1).DataContext as ViewModels.Windows1ViewModel;
			if (vm != null)
			{
				var word = new Model.WordsModel() { EnglishWord = Request.Content.TrimStart(), Translate = Result.TrimEnd() };
				char c = word.EnglishWord[0];
				if (Char.IsLower(c))
					word.EnglishWord = word.EnglishWord.Remove(0, 1).Insert(0, new string(char.ToUpper(c), 1));

				vm.Words.Add(word);
				vm.WordsCount = vm.Words.Count;
			}
		}

		private bool CanSaveExecute()
		{
			return !string.IsNullOrEmpty(Result);
		}

		public ICommand FileTranslaion { get { return new BaseCommand(FileExecuted, new Func<bool>(CanFileExecute)); } }
	
		private void FileExecuted()
		{
			this.CloseWindow.Execute(null);

			var vm = new ViewModels.FileTranslationViewModel();
			Views.FileTranslateView view = new Views.FileTranslateView();
			view.DataContext = vm;
			view.ShowInTaskbar = false;
			view.Owner = App.Current.MainWindow;
			view.WindowStyle = System.Windows.WindowStyle.ToolWindow;
			view.WindowStartupLocation = System.Windows.WindowStartupLocation.CenterOwner;
			view.ShowDialog();

			view.DataContext = null;
			view = null;
		}

		private bool CanFileExecute()
		{ return true; }
	}
}
